package com.dream.technology.components.context;

import com.dream.technology.db.entity.RcCustomerTag;
import com.dream.technology.db.entity.RcCustomerTagItem;
import com.dream.technology.db.entity.vo.VoCustomerTag;
import com.dream.technology.service.RcCustomerTagItemService;
import com.dream.technology.service.RcFlowParentService;
import com.dream.technology.service.RcFlowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 描述：解析用户标签 给用户打标签
 *
 * @author chen_q_i@163.com
 * 2018/12/25 : 14:37.
 * @version : 1.0
 */
@Component("tagContext")
public class TagContext {

    @Autowired
    private RcFlowService rcFlowService;
    @Autowired
    private RcFlowParentService parentService;
    @Autowired
    private RcCustomerTagItemService rcCustomerTagItemService;


    /**
     *  获取某个总流程下的所有用户标签
     * @param flowId
     * @return
     */
    public List<VoCustomerTag>  getVoTag(Long flowId){

        // 获取流程下所有的用户标签
        List<RcCustomerTag> customerTags = parentService.getVoTag(flowId);
        List<Long> tagIds = new ArrayList<>();
        customerTags.forEach(tag -> tagIds.add(tag.getId()));
        List<RcCustomerTagItem> rcCustomerTagItems = rcCustomerTagItemService.selectByTagIds(tagIds);
        Map<Long,List<RcCustomerTagItem>> items = new HashMap<>();
//       手动映射标签和 标签项的关系 避免多次查询
        rcCustomerTagItems.forEach(item ->{
            List<RcCustomerTagItem> tagItemsArr = items.get(item.getTagId());
            if (tagItemsArr==null){
                List<RcCustomerTagItem> tagItems = new ArrayList<>();
                tagItems.add(item);
                items.put(item.getTagId(),tagItems);
            }else {
                tagItemsArr.add(item);
                items.put(item.getTagId(),tagItemsArr);
            }
        });

        List<VoCustomerTag> voCustomerTags = new ArrayList<>();
        customerTags.forEach(tag-> {
            VoCustomerTag voCustomerTag = new VoCustomerTag();
            voCustomerTag.setCustomerTag(tag);
            voCustomerTag.setCustomerTagItems(items.get(tag.getId()));
            voCustomerTags.add(voCustomerTag);
        });
       return  voCustomerTags;
    }



}
